package com.cn.wanix.dao.impl;

import com.cn.wanix.dao.ProductDao;
import com.cn.wanix.model.CuisineModel;
import com.cn.wanix.model.ProductModel;
import com.cn.wanix.model.UserModel;
import com.cn.wanix.util.JDBC;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ProductImpl implements ProductDao {
    @Override
    public int add(ProductModel productModel) {
        return 0;
    }

    @Override
    public int update(ProductModel productModel) {
        return 0;
    }

    @Override
    public int delete(ProductModel productModel) {
        return 0;
    }

    @Override
    public List<ProductModel> findAll(ProductModel productModel) {
        String sql = "SELECT p.*,c.name cuisineName FROM product p\n" +
                ",cuisine c where p.cuisine_id=c.id";

        return setData(sql, null);
    }

    @Override
    public ProductModel findByID(ProductModel productModel) {
        return null;
    }

    @Override
    public int getCount(ProductModel productModel) {
        String sql = "SELECT count(*) count FROM product p\n" +
                ",cuisine c where p.cuisine_id=c.id";
        ResultSet query = JDBC.query(sql, null);
        try {
            while (query.next()) {
                return query.getInt("count");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    private List<ProductModel> setData(String sql, List<Object> data) {
        ResultSet query = JDBC.query(sql, data);
        List<ProductModel> list = new ArrayList<>();
        try {
            while (query.next()) {
                ProductModel model = new ProductModel();
                model.setId(query.getInt("id"));
                model.setName(query.getString("name"));
                model.setPrice(query.getFloat("price"));
                model.setNormalPrice(query.getFloat("normal_price"));
                model.setContent(query.getString("content"));
                model.setEnable(query.getInt("enable"));
                model.setImgHref(query.getString("img_href"));
                CuisineModel cuisineModel = new CuisineModel();
                cuisineModel.setName("cuisineName");
                model.setCuisineModel(cuisineModel);
                model.setUpdateTime(query.getString("update_time"));
                list.add(model);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
}
